import { Component, ViewChild, Host, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CompanyRiskRatingService } from '../companyRiskRating.service';
import { environment } from '../../../../../../environments/environment';
import { RatingOverviewMeiComponent } from './components/ratingOverview.component';
import { AnalystViewMeiComponent } from './components/analystView.component';
import { SubIndustryMeiComponent } from './components/subIndustry.component';
import { MeiIndicatorsComponent } from './components/indicators.component';
import { AppComponent } from '../../../../../app.component';
import { ClusterComponent } from '../../../riskCluster/cluster.component';
import { Subscription } from 'rxjs';
import { RiskMeiModel } from './models/riskMei.model';
import { UtilsService } from '../../../../../shared/services/utils.service';
import { AnalyticsService } from '../../../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../../../shared/models/googleAnalytics.model';

/**
 * MEI component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
  templateUrl: './mei.component.html',
  styleUrls: [
    '../companyRiskRating.component.scss',
    '../../company.component.scss',
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RiskMeiComponent extends ClusterComponent {
  private sub: Subscription;
  private meiSub: Subscription;
  private companySub: Subscription;
  private externalId: number;
  public type: string;
  public mei: RiskMeiModel;
  public subPeerGroup: string;
  public readonly resourcesUrl: string = environment.resourcesUrl;
  public formatIssueWeight: Function = UtilsService.formatIssueWeight;
  private promises: Promise<void>[];

  @ViewChild('ratingOverview') ratingOverview: RatingOverviewMeiComponent;
  @ViewChild('analystView') analystView: AnalystViewMeiComponent;
  @ViewChild('subIndustry') subIndustry: SubIndustryMeiComponent;
  @ViewChild('indicators') indicators: MeiIndicatorsComponent;

  constructor(
    @Host() private rootComponent: AppComponent,
    private route: ActivatedRoute,
    private cdRef: ChangeDetectorRef,
    private riskService: CompanyRiskRatingService,
    private analyticsService: AnalyticsService) {
    super(cdRef);
  }

  ngOnInit() {
    this.promises = [this.ratingOverview.loaded];
    this.sub = this.route.params.subscribe(params => {
      window.scrollTo(0, 0);
      this.externalId = params['externalId'];
      this.type = params['type'];      
      this.companySub = this.riskService.company.subscribe((company) => {        
        this.subPeerGroup = company.subPeerGroup;               
        this.riskService.mei = this.riskService.getMeiById(company.id, this.externalId);        
        this.meiSub = this.riskService.mei.subscribe((data) => {          
          this.mei = data;                              
          this.riskService.meiIndustryBenchmark = this.riskService.getCompanyMeiBenchmark(company.id, this.mei.externalId);
          this.riskService.meiIndustryExposure = this.riskService.getCompanyMeiSubIndustryExposure(company.id, this.mei.externalId);
          this.riskService.meiExposure = this.riskService.getMeiExposure(this.mei.externalId);
          this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESG RR MEIs', 'ESG Risk Rating', { CompanyId: company.id, MeiName: this.mei.name, ExternalId: this.externalId }));          
          this.cdRef.markForCheck();
          Promise.all(this.promises).then(() => {
            this.rootComponent.finishLoading();
          });
        }, error => this.errorCallback(_ => { this.mei = undefined; }, error));        
      });
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
    if(this.companySub) this.companySub.unsubscribe();
    if(this.meiSub) this.meiSub.unsubscribe();
  }
  
  get meiIcon() {
    const iconName = (this.mei.type === 'IdiosyncraticIssue' ? 999 : this.mei.externalId) + '_colored_large';
    return UtilsService.getIconFilename(iconName, 'riskRating');
  }

  get meiDescription(): string {
    switch (this.mei.externalId) {
      case 0: // MEI.0 - Corporate Governance
      case 113:
        return `Corporate Governance represents foundational structures for the management of ESG risks.`;
      case 1: // MEI.13 - Human Capital
        return `Human Capital focuses on the management of risks related to scarcity of skilled labour as well as labour relations, such as non-discrimination, working hours and minimum wages.`;
      case 2: // MEI.8 - Carbon - Own Operations
        return `Carbon - Own Operations refers to a company's management of risks related to its own operational energy use and GHG emissions (scope 1 and 2). It also includes parts of Scope 3 emissions.`;
      case 5: // MEI.7 - Emissions, Effluents and Waste
        return `Emissions, Effluents and Waste focuses on the management of emissions and releases from a company's own operations to air, water and land, excluding GHG emissions.`;
      case 8: // MEI.3 - Bribery and Corruption
        return `Bribery and Corruption focuses on the management of risks related to illicit payments, such as kickbacks or bribes to government officials or business partners, and the receipt of those payments.`;
      case 10: // MEI.6 - Data Privacy and Security
        return `Data Privacy and Security focuses on data governance practices, including how companies collect, use, manage and protect data.`;
      case 13: // MEI.14 - Land Use and Biodiversity
      case 112:
        return `Land Use and Biodiversity focuses on how companies' manage their impact on land, ecosystems and wildlife. Topics  include land conversion, land rehabilitation and forest management.`;
      case 14: // MEI.5 - Community Relations
        return `Community Relations focuses on how companies engage with local communities (including indigenous peoples) through both positive initiatives and mitigation of negative impacts.`;
      case 19: // MEI.19 - Resilience
        return `Resilience focuses on the financial stability and the management of related risks in the financial services industry, with emphasis on compliance with capital requirements.`;
      case 20: // MEI.4 - Business Ethics
        return `Business Ethics focuses on the management of ethical considerations applicable to most or all sectors, such as taxation and accounting, anti-competitive practices and intellectual property issues.`;
      case 31: // MEI.12 - Human Rights
        return `Human Rights focuses on how companies manage and respect fundamental human rights within their own operations.`;
      case 33: // MEI.9 - E&S Impact of Products and Services
        return `E&S Impact of Products and Services refers to the management of the inherent characteristics of input materials, and the impacts during use, disposal and recycling (excluding Carbon).`;
      case 34: // MEI.16 - Occupational Health and Safety
        return `Occupational Health and Safety focuses on the management of workplace hazards affecting a company's own employees and on-site contractors. Where relevant, it may also include HIV/AIDS programmes.`;
      case 35: // MEI.20 - Resource Use
        return `Resource Use focuses on how efficiently and effectively a company uses its raw material inputs (excluding energy and petroleum-based products) in production and how it manages related risks.`;
      case 36: // MEI.20.SC - Resource Use - Supply Chain
        return `Resource Use - Supply Chain focuses on companies' management water scarcity and raw material inputs risks (excluding energy and petroleum-based products) within its supply chain.`;
      case 37: // MEI.18 - Product Governance
        return `Product Governance focuses on how companies manage responsibilities to their clients. Emphasis is put on quality management systems, marketing practices, fair billing and post-sales responsibility.`;
      case 38: // MEI.1 - Access to Basic Services
        return `Access to Basic Services focuses on the management of access to essential products or services such as health care services and products to disadvantaged communities or groups.`;
      case 46: // MEI.12.SC - Human Rights - Supply Chain
        return `Human Rights - Supply Chain focuses on a company’s management of fundamental human rights issues occurring in its supply chain.`;
      case 47: // MEI.14.SC - Land Use and Biodiversity - Supply Chain
        return `Land Use and Biodiversity - Supply Chain focuses on how companies manage the impact of their suppliers' operations on land, ecosystems and wildlife.`
      case 49: // MEI.17 - ESG Integration - Financials
        return `ESG Integration - Financials includes all ESG integration activities by financial institutions that are either driven by financial downside risk considerations or by business opportunities.`;
      case 50: // MEI.8.PS - Carbon - Products & Services
        return `Carbon - Products and Services refers to a company's management of the energy efficiency and/or GHG emissions of its services and products during the use phase.`;
      default:
        return `An idiosyncratic issue is an issue that was not initially deemed material at the subindustry level but becomes a material
                ESG issue for a company based on the occurrence of a Category 4 or 5 event. Idiosyncratic issues are represented only by the respective event indicator.`;
    }
  }
}
